package com.tl.satoken.listener;

import com.tl.satoken.domain.entity.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketEventListener {
    private static final Logger log = LoggerFactory.getLogger(WebSocketEventListener.class);
    
    private final Map<String, Player> sessionPlayerMap = new ConcurrentHashMap<>();  // clientId -> Player


    public void addSessionPlayer(String sessionId, Player player) {
        sessionPlayerMap.put(sessionId, player);
        log.info("添加会话玩家映射: sessionId={}, playerId={}", sessionId, player.getId());
    }

    public void removeSessionPlayer(String sessionId) {
        Player player = sessionPlayerMap.remove(sessionId);
        if (player != null) {
            log.info("移除会话玩家映射: sessionId={}, playerId={}", sessionId, player.getId());
        }
    }

    public Player getPlayer(String sessionId) {
        return sessionPlayerMap.get(sessionId);
    }
    
    public Player getPlayerById(String playerId) {
        return sessionPlayerMap.values().stream() // 获取所有Player对象
                .filter(player -> playerId.equals(player.getId()))
                .findFirst()
                .orElse(null);
    }

    public List<Player> getPlayerById1() {
        return sessionPlayerMap.values().stream().toList();
    }

    public Map<String, Player> getSessionPlayerMap() {
        return sessionPlayerMap;
    }
    
    /**
     * 清理无效的session
     */
    public void cleanupInvalidSessions() {
        sessionPlayerMap.entrySet().removeIf(entry -> {
            Player player = entry.getValue();
            if (player.getChannel() != null) {
                boolean isValid = player.getChannel().channel().isActive();
                if (!isValid) {
                    log.info("清理无效session: sessionId={}, playerId={}", entry.getKey(), player.getId());
                }
                return !isValid;
            }
            return true; // 移除没有channel的session
        });
    }
    
    /**
     * 获取有效的session数量
     */
    public int getValidSessionCount() {
        return (int) sessionPlayerMap.values().stream()
                .filter(player -> player.getChannel() != null && player.getChannel().channel().isActive())
                .count();
    }

}
